const db = require("../db/index");
const bcrypt = require("bcryptjs");

exports.updateInfo = (req, res) => {
  const sql = "UPDATE users SET ? WHERE id = ?";
  console.log(req.body);

  const user_id = req.body.id;
  console.log(user_id);
  const { nickname, phone, email, avatar, website, bio } = req.body;
  db.query(
    sql,
    [{ nickname, phone, email, avatar, website, bio }, user_id],
    (err, result) => {
      if (err) {
        res.cc(err);
      }
      if (result.affectedRows !== 1) {
        return res.cc("更新用户信息失败");
      }
      res.send({
        status: 0,
        message: "更新用户信息成功",
      });
    }
  );
};

exports.updatePwd = (req, res) => {
  const user_id = req.body.id;

  const { oldPwd, newPwd } = req.body;
  const sql = "SELECT * FROM users WHERE id =?";
  db.query(sql, user_id, (err, result) => {
    const compareResult = bcrypt.compareSync(oldPwd, result[0].password);
    if (!compareResult) {
      return res.cc("原密码错误");
    }
    const sql = "UPDATE users SET password =? WHERE id =?";
    const newPassword = bcrypt.hashSync(newPwd, 10);
    db.query(sql, [newPassword, user_id], (err, result) => {
      if (err) {
        res.cc(err);
      }
      if (result.affectedRows !== 1) {
        return res.cc("更新密码失败");
      }
      res.send({
        status: 0,
        message: "更新密码成功",
      });
    });
  });
};
